package com.joolun.common.utils.msg;

import com.alibaba.fastjson.JSONObject;
import com.joolun.common.exception.CustomException;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.apache.http.HttpEntity;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Date;

/**
 * @author yto_xx
 * @DATE 2021-02-23 15:35
 */
public class MsgUtil {

    // 在MiaoxinSmsClient.java 类里面最上面的三个参数
    private static final String account = "ch00ap"; // 你的短信子账号App_ID（非登陆账号）
    private static final String secret = "ghy8nxmtfr"; // 你的短信子账号的App_SECRET
    // 密匙（非登陆密码）
    private static final String server = "http://129.211.186.18/sms/send";
    private static final String msgHeader = "【小牛量化】";
    private static final String contentTemp = "尊敬的用户，您本次操作的验证码为 %s ，请妥善保存，切勿泄露,该码有效期为2分钟。";

    /**
     * template 带有 %s 占位符来填充验证码；
     *
     * @param mobiles
     * @param template
     */
    public String sendCustomMsg(String mobiles, String template) {

        // 将application/x-www-from-urlencoded字符串转换成普通字符串
        // String keyWord = URLDecoder.decode("%C4%E3%BA%C3", "GBK");
        // System.out.println(keyWord); //输出你好

        int randNum = (int) (Math.random() * 999999 + 1);

        String pattern = "yyyyMMddHHmmss";
        String ts = DateFormatUtils.format(new Date(), pattern);
        String sha1Str = "account=" + account + "&ts=" + ts + "&secret=" + secret;
        String token = DigestUtils.sha1Hex(sha1Str);

        String content = "";
        try {
            String msg = "";
            if (!StringUtils.isEmpty(template)) {
                msg = msgHeader + template;
            } else {
                msg = String.format(msgHeader + contentTemp, randNum);
            }
            // 将普通字符创转换成application/x-www-from-urlencoded字符串
            content = URLEncoder.encode(msg, "UTF-8"); // 输出%C4%E3%BA%C3
        } catch (UnsupportedEncodingException e) {
//            e.printStackTrace();
            throw new CustomException("短信接口异常", e);
        }

//        doPost(server, sha1Str + "&token=" + token + "&mobiles=" + mobiles + "&content=" + content);
        doPost(server, "account=" + account + "&token=" + token + "&ts=" + ts + "&mobiles=" + mobiles + "&content=" + content);
        return randNum + "";
    }

    public String doGet(String url) {
        CloseableHttpClient httpClient = null;
        CloseableHttpResponse response = null;
        String result = "";
        try {
            // 通过默认配置创建一个httpClient实例
            httpClient = HttpClients.createDefault();
            // 创建httpGet远程连接实例
            HttpGet httpGet = new HttpGet(url);
            // httpGet.addHeader("Connection", "keep-alive");
            // 设置请求头信息
            httpGet.addHeader("Accept", "application/json");
            // 配置请求参数
            RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(35000) // 设置连接主机服务超时时间
                    .setConnectionRequestTimeout(35000)// 设置请求超时时间
                    .setSocketTimeout(60000)// 设置数据读取超时时间
                    .build();
            // 为httpGet实例设置配置
            httpGet.setConfig(requestConfig);
            // 执行get请求得到返回对象
            response = httpClient.execute(httpGet);
            // 通过返回对象获取返回数据
            HttpEntity entity = response.getEntity();
            // 通过EntityUtils中的toString方法将结果转换为字符串，后续根据需要处理对应的reponse code
            result = EntityUtils.toString(entity);
            System.out.println(result);

        } catch (Exception e) {
            e.printStackTrace();
            throw new CustomException("短信接口异常", e);
        } finally {
            // 关闭资源
            if (response != null) {
                try {
                    response.close();
                } catch (IOException ioe) {
                    ioe.printStackTrace();
                }
            }
            if (httpClient != null) {
                try {
                    httpClient.close();
                } catch (IOException ioe) {
                    ioe.printStackTrace();
                }
            }
        }
        return result;
    }

    public String doPost(String url, String content) {
        // 创建httpClient对象
        CloseableHttpClient httpClient = HttpClients.createDefault();
        CloseableHttpResponse response = null;
        String result = "";
        try {
            // 创建http请求
            HttpPost httpPost = new HttpPost(url);
            httpPost.addHeader("Content-Type", "application/x-www-form-urlencoded");
            // 创建请求内容
            StringEntity entity = new StringEntity(content);
            httpPost.setEntity(entity);
            response = httpClient.execute(httpPost);
            result = EntityUtils.toString(response.getEntity(), "utf-8");

            CoinMsgResult re = JSONObject.parseObject(result, CoinMsgResult.class);
            String errMobiles = "";
            for (OrderResult codeRes : re.getResult()) {
                if (codeRes.getCode() != 0) {
                    errMobiles += codeRes.getMobile() + ",";
                }
            }
            if (StringUtils.isNotEmpty(errMobiles)) {
                throw new CustomException(errMobiles + "短信发送异常");
            }

        } catch (Exception e) {
            e.printStackTrace();
            throw new CustomException("短信接口异常", e);
        } finally {
            // 关闭资源
            if (response != null) {
                try {
                    response.close();
                } catch (IOException ioe) {
                    ioe.printStackTrace();
                }
            }
            if (httpClient != null) {
                try {
                    httpClient.close();
                } catch (IOException ioe) {
                    ioe.printStackTrace();
                }
            }
        }
        return result;
    }
}
